# -*- coding: utf-8 -*-

import json
import sys

# from util.g import g
from util.pdfSplit import g
from util.pdfSplit import POOL, dict_cursor
from settings import web_type


class get_catalogue():
    type_table_map = {"ip": "ent_res_ipr", "rd": "ent_res_rd", "ps": "ent_res_ps", "sta": "ent_res_sta",
                      "std": "ent_res_stand"}

    def __init__(self, co_id, year, web_type):
        self.co_id = co_id
        self.year = year
        self.web_type = web_type

    def __call__(self, *args, **kwargs):
        pdf_rule = self.get_pdf_rule(web_type=self.web_type)
        pdf_rule_value = pdf_rule.get("pdf_rule")
        # print(pdf_rule_value)
        jsonObject = None if pdf_rule_value == None else json.loads(pdf_rule_value).get("content")
        single_cata = self.get_cata_from_entrespdf(co_id=self.co_id, year=self.year, web_type=self.web_type)
        for i in jsonObject:
            self.ruleHandle(ruleEle=i, entResPdfList=single_cata)
            if i.get("children") != None:
                for chil in i.get("children"):
                    self.ruleHandle(chil, single_cata)
            if i.get("mode") == "one-to-one":
                self.get_cata_from_detail(co_id=self.co_id, year=self.year, ruleEle=i, entResPdfList=single_cata)

        return single_cata

    def ruleHandle(self, ruleEle, entResPdfList):
        res_id = ruleEle.get("id")
        for i in entResPdfList:
            if (i.get("rule_id") == res_id):
                i["type"] = ruleEle.get("type")
                i["size"] = ruleEle.get("size")
                i["calculate"] = ruleEle.get("calculate")

    def get_cata_from_entrespdf(self, co_id=None, year=None, web_type=None):
        select_sql = """select co_id, year, web_type, rule_id, res_name, file_start, file_end, res_code, oss_path from ent_res_pdf where co_id={} and year={} and web_type='{}'""".format(
            co_id, year, web_type)
        client = POOL.connection()
        cursor = client.cursor(dict_cursor)

        data = None
        try:
            cursor.execute(select_sql)
            data = cursor.fetchall()
        except Exception as err:
            g.logger.error("{} select cata from ent_res_pdf error co_id={} year={} web_type='{}'".format(
                sys._getframe().f_code.co_name, co_id, year, web_type))
        finally:
            cursor.close()
            client.close()
        return data

    def get_pdf_rule(self, web_type=None):
        select_sql = """select pdf_rule from ent_pdfrule where web_type='{}'""".format(web_type)
        client = POOL.connection()
        cursor = client.cursor(dict_cursor)

        data = None
        try:
            cursor.execute(select_sql)
            data = cursor.fetchone()
        except Exception as err:
            g.logger.error(
                "{} select pdf_rule from ent_pdfrule error web_type={}".format(sys._getframe().f_code.co_name,
                                                                               web_type))
        finally:
            cursor.close()
            client.close()
        return data

    def get_cata_from_detail(self, co_id, year, ruleEle, entResPdfList):
        fields = [a.get("field_db") for a in ruleEle.get("fields") if a.get("field_db") != "file_path"]
        # fields.pop("file_path")
        # 增加一个 oss_path 字段
        fields.append("oss_path")
        select_sql = """select {} from {} where co_id={} and year={}""".format(",".join(fields),
                                                                               self.type_table_map.get(
                                                                                   ruleEle.get("type")),
                                                                               co_id,
                                                                               year)
        select_sql = select_sql.replace(",,", ",")
        client = POOL.connection()
        cursor = client.cursor(dict_cursor)
        data = None
        try:
            cursor.execute(select_sql)
            data = cursor.fetchall()
        except Exception as err:
            g.logger.error("{} select detail cata error co_id={} year={} type={}".format(sys._getframe().f_code.co_name,
                                                                                         co_id,
                                                                                         year,
                                                                                         type=ruleEle.get("type")))
        finally:
            cursor.close()
            client.close()
        for i in data:
            i["type"] = ruleEle.get("type")
            i["size"] = ruleEle.get("size")
            if all([i.get("file_start"), i.get("file_end")]):
                entResPdfList.append(i)


if __name__ == '__main__':
    gc = get_catalogue(co_id=115540, year=2021, web_type=web_type)
    print(gc())
